import React, { Component } from "react"
import { createStore } from "redux"

// reducer
const counter = (state = {num1: 0, num2: 0, total: 0}, action) => {
  switch(action.type) {
    case 'CHANGEN1':
      return {...state, num1: action.n1}
    case 'CHANGEN2':
      return {...state, num2: action.n2}
    case 'INCREMENT':
      return {...state, total: state.num1 + state.num2}
    case 'DECREMENT':
      return {...state, total: state.num1 - state.num2}
    case 'MULTIPLY':
      return {...state, total: state.num1 * state.num2}
    case 'DIVIDE':
      return {...state, total: state.num1 / state.num2}
    default:
      return state
  }
}

// action
function changen1(n1) {
  return { type: 'CHANGEN1', n1 }
}

function changen2(n2) {
  return { type: 'CHANGEN2', n2 }
}

// store
let store = createStore(counter)

class Counter extends Component {
  constructor(props) {
    super(props)
    this.state = {
      num1: 0,
      num2: 0,
      total: 0
    }
  }

  render() {
    return (
      <div className="Counter-container">
        <input type="number" className="num1" value={this.state.num1} onChange={this.onChangeN1}></input>
        <input type="number" className="num2" value={this.state.num2} onChange={this.onChangeN2}></input>
        <br></br>
        <button onClick={this.onClickAdd}>+</button>
        <button onClick={this.onClickMin}>-</button>
        <button onClick={this.onClickMul}>*</button>
        <button onClick={this.onClickDiv}>/</button>
        <br></br>
        <span>total: {this.state.total}</span>                                          
      </div>
    )
  }

  onChangeN1 = async (e) => {
    await this.setState((state) => ({
      num1: e.target.value
    }))
    store.dispatch(changen1(Number(this.state.num1)))
  }

  onChangeN2 = async (e) => {
    await this.setState((state) => ({
      num2: e.target.value
    }))
    store.dispatch(changen2(Number(this.state.num2)))
  }

  onClickAdd = () => {
    store.dispatch({ type: 'INCREMENT' })
    this.getTotal()
  }

  onClickMin = () => {
    store.dispatch({ type: 'DECREMENT' })
    this.getTotal()
  }

  onClickMul = () => {
    store.dispatch({ type: 'MULTIPLY' })
    this.getTotal()
  }

  onClickDiv = () => {
    store.dispatch({ type: 'DIVIDE' })
    this.getTotal()
  }

  getTotal = () => {
    this.setState((state) => ({
      total: store.getState().total
    }))
  }
}

function App() {
  return (
    <div className="App">
      <Counter></Counter>
    </div>
  );
}

export default App;
